/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function (matrix) {
    let row = matrix.length // 行
    let column = matrix[0].length // 列
    let arr = []

    let dir = -1
    let dirList = [[0, 1], [1, 0], [0, -1], [-1, 0]]
    function direction() {
        dir++
        return dirList[dir % 4]
    }
    let i = 0;
    let j = 0;
    let total = row * column
    let count = 1
    let d = direction()

    while (count <= total) {

        if ((i + d[0]) < 0 || (i + d[0]) >= row || (j + d[1] < 0 || (j + d[1]) >= column)) {
            d = direction()
        }
        
        arr.push(matrix[i][j])
        matrix[i][j] = 'null'


        i = i + d[0]
        j = j + d[1]
        if (matrix[i] && matrix[i][j] && matrix[i][j] == 'null') {
            i = i - d[0]
            j = j - d[1]
            d = direction()
            i = i + d[0]
            j = j + d[1]
        }

        count++
    }

    return arr
};
console.log(generateMatrix([[1,2,3,4],[5,6,7,8],[9,10,11,12]]));
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]